<template>
  <el-aside width="200px" class="sidebar">
    <el-menu
      :default-active="activeIndex"
      class="sidebar-menu"
    >
      <el-menu-item 
        v-for="route in visibleRoutes" 
        :key="route.name" 
        :index="route.name"
        @click="handleSelect(route)"
      >
        <el-icon v-if="route.meta?.menu?.icon && !route.meta?.menu?.icon.startsWith('i-')">
          <component :is="icons[route.meta.menu.icon]" />
        </el-icon>
        <svg v-else-if="route.meta?.menu?.icon && route.meta?.menu?.icon.startsWith('i-')" class="icon" aria-hidden="true">
          <use :xlink:href="'#' + route.meta.menu.icon"></use>
        </svg>
        <span>{{ route.meta?.menu?.title || route.name }}</span>
      </el-menu-item>
    </el-menu>
  </el-aside>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  Promotion, 
  DataAnalysis,
  House,
  User,
  Document,
  ChatLineSquare,
  Bell,
  Monitor 
} from '@element-plus/icons-vue'
import { isPageVisible } from '@/utils/permission'

// 定义组件属性
interface Props {
  basePath: string
  routes: any[]
  redirectFirst?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  redirectFirst: true
})

// 图标映射
const icons: Record<string, any> = {
  Promotion,
  DataAnalysis,
  House,
  User,
  Document,
  ChatLineSquare,
  Bell,
  Monitor
}

const router = useRouter()
const route = useRoute()

// 当前激活的菜单索引
const activeIndex = ref('')

// 根据权限过滤可见路由
const visibleRoutes = computed(() => {
  return props.routes.filter(r => {
    if (!r.meta?.menu) return false
    // 根据路由名称找到对应的权限分类键名
    const permissionKey = r.path || ''
    // 根据权限控制菜单显示
    return isPageVisible(permissionKey)
  })
})

// 处理菜单选择
const handleSelect = (selectedRoute: any) => {
  if (selectedRoute) {
    const fullPath = `${props.basePath}/${selectedRoute.path}`
    router.push(fullPath)
  }
}

// 监听路由变化，同步更新激活的菜单项
watch(
  () => route.path,
  (newPath) => {
    // 查找匹配的子路由
    const matchedRoute = visibleRoutes.value.find(r => 
      newPath === `${props.basePath}/${r.path}` || 
      (r.path === '' && newPath === props.basePath)
    )
    
    if (matchedRoute) {
      activeIndex.value = matchedRoute.name as string
    } else if (newPath === props.basePath && props.redirectFirst) {
      // 默认激活并跳转到第一个子路由
      const firstRoute = visibleRoutes.value.find(r => r.path !== '' && r.meta?.menu)
      if (firstRoute) {
        activeIndex.value = firstRoute.name as string
        // 自动跳转到第一个子路由
        nextTick(() => {
          handleSelect(firstRoute)
        })
      }
    }
  },
  { immediate: true }
)

// 在组件挂载时检查是否需要跳转到默认子路由
onMounted(() => {
  if (route.path === props.basePath && props.redirectFirst) {
    const firstRoute = visibleRoutes.value.find(r => r.path !== '' && r.meta?.menu)
    if (firstRoute) {
      nextTick(() => {
        handleSelect(firstRoute)
      })
    }
  }
})
</script>

<style scoped>
.sidebar {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
  overflow: hidden;
  height: 100%;
}

.sidebar-menu {
  border-right: none;
  height: 100%;
}

:deep(.el-menu-item.is-active) {
  background-color: #e6f7ff;
  color: #409eff;
}

:deep(.el-menu-item.is-active)::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background-color: #409eff;
}

/* 调整 Element Plus 图标大小 */
:deep(.el-menu-item .el-icon) {
  width: 16px;
  height: 16px;
  font-size: 16px;
}

/* 调整自定义图标大小 */
.icon {
  width: 16px;
  height: 16px;
  font-size: 16px;
  vertical-align: middle;
  margin-right: 5px;
  fill: currentColor;
  overflow: hidden;
}
</style>